package top.lingkang.acgv.config.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import top.lingkang.acgv.acr.entity.Role;
import top.lingkang.acgv.acr.po.auth.AuthGrantedAuthority;
import top.lingkang.acgv.acr.po.auth.AuthUser;
import top.lingkang.acgv.service.UserService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 绫小路
 * @date 2021/7/21 21:28
 * @description 自定义账号密码验证
 */
@Component
public class LoginUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;

    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        top.lingkang.acgv.acr.entity.User user = userService.getUser(s);
        if (user == null) {
            new UsernameNotFoundException("账号或密码错误");
        }
        // AuthGrantedAuthority 为实现GrantedAuthority的自定义
        List<AuthGrantedAuthority> authorityList = new ArrayList<>();
        List<Role> roles = userService.getRoleList(user.getId());
        roles.forEach(r -> {
            authorityList.add(new AuthGrantedAuthority(r.getName()));
        });
        AuthUser authUser = new AuthUser(s, user.getPassword(), authorityList);
        authUser.setSex(user.getSex());
        authUser.setNickname(user.getNickname());
        authUser.setStatus(user.getStatus());
        return authUser;
    }
}
